package com.xiyang.security.config.security;

import com.xiyang.security.config.security.authorization.CustomFilterSecurityInterceptor;
import com.xiyang.security.config.security.handler.LoginFailureHandler;
import com.xiyang.security.config.security.handler.LoginSuccessHandler;
import com.xiyang.security.config.security.jwt.JwtAuthorizationTokenFilter;
import com.xiyang.security.config.security.verif.VerifyCodeFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 *
 * SecurityContextPersistenceFilter
 * {@link org.springframework.security.web.context.SecurityContextPersistenceFilter}
 * 该类在所有的filter之前，是从{@link org.springframework.security.web.context.SecurityContextRepository}取出用户认证信息，
 * 默认实现类@{@link org.springframework.security.web.context.HttpSessionSecurityContextRepository},
 * 其会从Session中取出已认证用户的信息，提高效率，避免每一次请求都要查询用户认证信息。
 * 取出之后会放入{@link org.springframework.security.core.context.SecurityContextHolder}中，以便其他filter使用，
 * SecurityContextHolder使用ThreadLocal存储用户认证信息，保证了线程之间的信息隔离，最后再finally中清楚该信息
 *                                      ⇩
 *
 * @author xiyang.ycj
 * @since Jun 25, 2019 01:52:43 AM
 */
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private LoginSuccessHandler successHandler;
    @Autowired
    private LoginFailureHandler failureHandler;
    @Autowired
    private VerifyCodeFilter verifyCodeFilter;
    @Autowired
    private CustomUserDetailsService userDetailsService;
    @Autowired
    private CustomFilterSecurityInterceptor filterSecurityInterceptor;
    @Autowired
    private JwtAuthorizationTokenFilter jwtAuthorizationTokenFilter;

    /**
     * spring5.0之后，spring security必须设置加密方法否则会报
     * There is no PasswordEncoder mapped for the id "null"
     * @return 加密
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder(4);
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/logins","/login_page","/home","/getCode").permitAll()
                .anyRequest().authenticated()
                .and()
                //.httpBasic();
                .formLogin()
                .loginPage("/login_page")
                .loginProcessingUrl("/login")
                .successHandler(successHandler)
                .failureHandler(failureHandler)
                .and()
                .logout()
                .logoutSuccessUrl("/home");

        http.csrf().disable(); /* CSRF禁用,因为不使用session */
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER); /* 禁用session */
        http.addFilterBefore(verifyCodeFilter, UsernamePasswordAuthenticationFilter.class);
        http.addFilterAt(filterSecurityInterceptor, FilterSecurityInterceptor.class);
        http.addFilterBefore(jwtAuthorizationTokenFilter,UsernamePasswordAuthenticationFilter.class);
    }
}
